package cn.edu.nit.sys.service.impl;

import cn.edu.nit.sys.entity.Employee;
import cn.edu.nit.sys.mapper.EmployeeMapper;
import cn.edu.nit.sys.service.EmployeeService;
import cn.edu.nit.sys.utils.R;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author xiaobai
 * @Date 2022/9/26 21:34
 * @Version 1.0.0
 */
@Service
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 获取所有员工列表
     * @param page
     * @param name
     * @return
     */
    @Override
    public R getList(Page<Employee> page, String name, Integer type) {
        Page<Employee> list = baseMapper.getList(page, name, type);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", list.getTotal());
        jsonObject.put("list", list.getRecords());
        return R.ok(jsonObject);
    }

    @Override
    public R getType() {
        List<Map<Object, Object>> list = baseMapper.getType();
        return R.ok(list);
    }

    @Override
    public R addEmployee(Employee employee) {
        employee = setTypeName(employee);
        return baseMapper.insert(employee) > 0 ? R.ok("添加成功") : R.error("添加失败");
    }

    @Override
    public R updateEmployee(Employee employee) {
        employee = setTypeName(employee);
        return baseMapper.updateById(employee) > 0 ? R.ok("修改成功") : R.error("修改失败");
    }

    @Override
    public R delEmployee(Long id) {
        return baseMapper.deleteById(id) > 0 ? R.ok("删除成功") : R.error("删除失败");
    }

    @Override
    public R getEmpByType() {
        List<Map<Object, Object>> maps = baseMapper.getEmpByType();
        return R.ok(maps);
    }

    private Employee setTypeName(Employee employee) {
        List<Map<Object, Object>> type = employeeMapper.getType();
        for(Map<Object, Object> map : type) {
            if(map.get("id").equals(employee.getTypeCode())) {
                employee.setTypeName(map.get("name").toString());
            }
        }
        return employee;
    }
}
